<?php
/**
 * Author: FoxxxZhu
 * Date: 2016/11/2
 * Time: 11:01
 */

namespace Forxx;
use Lavender\Core;
use Lavender\Errno;
use Lavender\Exception;
use Lavender\Filter;

class ForxxAESApiService extends ForxxWebService{
    protected $without_sign_actions = array();
    protected $without_auth_actions = array('*');
    protected static $_decrypt_raw_body = null;

    protected static function get_raw_body()
    {
        if(empty(self::$_decrypt_raw_body))
        {
            self::$_raw_body = file_get_contents("php://input");
            $keys = Core::get_config("const","AES_SECRET");
            $appId = isset($_GET['app_id']) ? $_GET['app_id'] : "";
            if(empty($appId)){
                throw new Exception("app_id is required!");
            }
            if(isset($keys[$appId])){
                $conf = $keys[$appId];
            }
            else{
                throw new Exception("app_id is error!");
            }
            if(!empty(self::$_raw_body)){
                $decrypttext = openssl_decrypt(self::$_raw_body, $conf['method'],  base64_decode($conf['pass']), $options=0, base64_decode($conf['iv']));
                if(empty($decrypttext)){
                    throw new Exception("post content is error!");
                }
//                $postData = @json_decode($ciphertext,true);
//                if(!is_array($postData)){
//                    throw new Exception("post content data  is error!");
//                }
                self::$_decrypt_raw_body = $decrypttext;
            }
        }
        return self::$_decrypt_raw_body;
    }

    protected function get_request_param()
    {
        $request = array();
        if (!empty($_GET)) {
            foreach ($_GET as $key => $value) {
                $request[$key] = $value;
            }
        }
        if (!empty($_POST)) {
            foreach ($_POST as $key => $value) {
                $request[$key] = $value;
            }
        }
        self::get_raw_body();
        $input = self::$_raw_body;
        if(!empty($input))
        {
            $request['_input'] = $input;
        }
        return $request;
    }

    protected function check_sign()
    {
        if($this->need_sign){
            $sign_field_name = $this->sign_field_name;
            $req = array(
                'ver' => Filter::T_STRING,
                'token' => Filter::T_STRING,
                $sign_field_name => Filter::T_STRING,
            );
            $params = $this->parameters($req, self::M_GET, true);
            $this->sign = $params[$sign_field_name];
            $request = $this->get_request_param();
            $token = $params['token'];
            if(empty($token))
            {
                throw new Exception\Auth('token missed', Errno::AUTH_FAILED);
            }
            if(empty($this->sign))
            {
                throw new Exception\Auth($sign_field_name.' missed', Errno::AUTH_FAILED);
            }
            if(!$this->is_valid_signature($token, $request, $this->sign))
            {
                throw new Exception\Auth('sign verify failed : '.$this->sign, Errno::AUTH_FAILED);
            }
        }
    }

    public function render($__data__ = null, $__view__ = null)
    {
        //get friend message
        if (isset($__data__['code']) && $__data__['code'] > 0) {
            $msg = isset($__data__['msg'])?$__data__['msg']:'';
            if(!empty($msg))
            {
                $__data__['msg'] = $msg;
            }
        }

        //json
        //$__data__['code'] = (string)$__data__['code'];
        $response = json_encode($__data__, JSON_UNESCAPED_UNICODE);

        $keys = Core::get_config("const","AES_SECRET");
        $appId = isset($_GET['app_id']) ? $_GET['app_id'] : "";
        if(empty($appId)){
            echo "app_id is required!";
            exit();
        }
        if(isset($keys[$appId])){
            $conf = $keys[$appId];
        }
        else{
            echo "app_id is error!";
            exit();
        }
        $ciphertext  = openssl_encrypt($response, $conf['method'],  base64_decode($conf['pass']), $options=0, base64_decode($conf['iv']));
        echo $ciphertext;
        //write session flow
        $this->session_flow($__data__);
    }

    public function success($msg = '', $data = null){
        $this->header_content_type("text/plain");
        $result = [];
        $result['code'] = 0;
        $result['msg'] = $msg;
        $result['data'] = $data;
        return $result;
    }

    public function error($msg = '', $code = -1){
        $this->header_content_type("text/plain");
        $result = [];
        $result['code'] = 0;
        $result['msg'] = $msg;
        return $result;
    }

}